var commonCityData = require('../../utils/city.js')
//获取应用实例
var app = getApp()
const PROVINCE = 0, CITY = 1, DISTRICT = 2

Page({
  data: {
    id: 0,
    name: '',
    phone: '',
    address: '',
    provinces:[],
    provincesID: [],
    cities:[],
    citiesID: [],
    districts:[],
    districtsID: [],
    selProvince:'请选择',
    selCity:'请选择',
    selDistrict:'请选择',
    selProvinceIndex: 0,
    selProvinceID: '',
    selCityIndex: 0,
    selCityID: '',
    selDistrictIndex: 0,
    selDistrictID: '',
    type: 0
  },
  bindCancel:function () {
    wx.navigateBack({})
  },
  bindSave: function(e) {
    let that = this;
    let contact = {}
    contact.name = e.detail.value.linkMan;
    contact.address = e.detail.value.address;
    contact.phone = e.detail.value.mobile;
    contact.code = e.detail.value.code;
    

    if (contact.name == ""){
      wx.showModal({
        title: '提示',
        content: '请填写联系人姓名',
        showCancel:false
      })
      return
    }
    if (contact.phone == ""){
      wx.showModal({
        title: '提示',
        content: '请填写手机号码',
        showCancel:false
      })
      return
    }

    // for-test
    // this.data.selProvince = "北京"
    // this.data.selCity = "北京"
    // this.data.selDistrict = "朝阳区"

    if (this.data.selProvince == "请选择" || this.data.selCity == "请选择" || this.data.selDistrict == "请选择"){
      wx.showModal({
        title: '提示',
        content: '请选择地区',
        showCancel:false
      })
      return
    }
  
    if (contact.address == ""){
      wx.showModal({
        title: '提示',
        content: '请填写详细地址',
        showCancel:false
      })
      return
    }
    
    contact.selProvince = this.data.selProvince
    contact.selProvinceID = this.data.selProvinceID
    contact.selCity = this.data.selCity
    contact.selCityID = this.data.selCityID
    contact.selDistrict = this.data.selDistrict
    contact.selDistrictID = this.data.selDistrictID
    contact.id = this.data.id

    this.addcontact(contact, e.detail.formId)
    console.log('formID:' + e.detail.formId)


    // if (code == ""){
    //   wx.showModal({
    //     title: '提示',
    //     content: '请填写邮编',
    //     showCancel:false
    //   })
    //   return
    // }
    // var apiAddoRuPDATE = "add";
    // var apiAddid = that.data.id;
    // if (apiAddid) {
    //   apiAddoRuPDATE = "update";
    // } else {
    //   apiAddid = 0;
    // }
    // wx.request({
    //   url: 'https://api.it120.cc/' + app.globalData.subDomain + '/user/shipping-address/' + apiAddoRuPDATE,
    //   data: {
    //     token: app.globalData.token,
    //     id: apiAddid,
    //     provinceId: commonCityData.cityData[this.data.selProvinceIndex].id,
    //     cityId: cityId,
    //     districtId: districtId,
    //     linkMan:linkMan,
    //     address:address,
    //     mobile:mobile,
    //     code:code,
    //     isDefault:'true'
    //   },
    //   success: function(res) {
    //     if (res.data.code != 0) {
    //       // 登录错误 
    //       wx.hideLoading();
    //       wx.showModal({
    //         title: '失败',
    //         content: res.data.msg,
    //         showCancel:false
    //       })
    //       return;
    //     }
    //     // 跳转到结算页面
    //     wx.navigateBack({})
    //   }
    // })
  },
  // initCityData:function(level, obj){
  //   if(level == 1){
  //     var pinkArray = [];
  //     for(var i = 0;i<commonCityData.cityData.length;i++){
  //       pinkArray.push(commonCityData.cityData[i].name);
  //     }
  //     this.setData({
  //       provinces:pinkArray
  //     });
  //   } else if (level == 2){
  //     var pinkArray = [];
  //     var dataArray = obj.cityList
  //     for(var i = 0;i<dataArray.length;i++){
  //       pinkArray.push(dataArray[i].name);
  //     }
  //     this.setData({
  //       cities:pinkArray
  //     });
  //   } else if (level == 3){
  //     var pinkArray = [];
  //     var dataArray = obj.districtList
  //     for(var i = 0;i<dataArray.length;i++){
  //       pinkArray.push(dataArray[i].name);
  //     }
  //     this.setData({
  //       districts:pinkArray
  //     });
  //   }
    
  // },
  bindPickerProvinceChange: function(event){
    var selItem = this.data.provinces[event.detail.value]
    var selItemID = this.data.provincesID[event.detail.value]
    this.setData({
      selProvince: selItem,
      selProvinceIndex: event.detail.value,
      selProvinceID: selItemID,
      selCity: '请选择',//selIterm.name != ('北京市' || '天津市' || '重庆市' || '上海市') ? '请选择' : selIterm.name,
      selCityIndex:0,
      selDistrict: '请选择',
      selDistrictIndex: 0
    })
    this.getCities(selItemID, CITY)
    //this.initCityData(2, selIterm)
  },
  bindPickerCityChange:function (event) {
    var selItem = this.data.cities[event.detail.value]
    var selItemID = this.data.citiesID[event.detail.value]
    this.setData({
      selCity: selItem,
      selCityID: selItemID,
      selCityIndex: event.detail.value,
      selDistrict: '请选择',
      selDistrictIndex: 0
    })
    this.getDistricts(selItemID, DISTRICT)
    //this.initCityData(3, selIterm)
  },
  bindPickerChange:function (event) {
    var selItem = this.data.districts[event.detail.value]
    var selItemID = this.data.districtsID[event.detail.value]
   
    this.setData({
      selDistrict: selItem,
      selDistrictID: selItemID,
      selDistrictIndex: event.detail.value
    })
    
  },
  onLoad: function (e) {
    var that = this;
    var type = e.type
    if (type == 1) {
      this.getAddress(e.id)
      this.setData({
        id: e.id
      })  
    }
    this.setData({
      type: type
    })
  },
  onShow() {
    this.getProvinces(1, PROVINCE)
  },	
  setDBSaveAddressId: function(data) {
    var retSelIdx = 0;
    for (var i = 0; i < commonCityData.cityData.length; i++) {
      if (data.provinceId == commonCityData.cityData[i].id) {
        this.data.selProvinceIndex = i;
        for (var j = 0; j < commonCityData.cityData[i].cityList.length; j++) {
          if (data.cityId == commonCityData.cityData[i].cityList[j].id) {
            this.data.selCityIndex = j;
            for (var k = 0; k < commonCityData.cityData[i].cityList[j].districtList.length; k++) {
              if (data.districtId == commonCityData.cityData[i].cityList[j].districtList[k].id) {
                this.data.selDistrictIndex = k;
              }
            }
          }
        }
      }
    }
  },

  /**
   * 获取省份列表
   */
  getProvinces: function (countryID, type) {
    this.getlocationlist(countryID, PROVINCE)
  },

  /**
   * 获取市列表
   */
  getCities: function (provinceID, type) {
    this.getlocationlist(provinceID, CITY)
  },

  /**
   * 获取区列表
   */
  getDistricts: function (cityID, type) {
    this.getlocationlist(cityID, DISTRICT)
  },

  /**
   * 获取地址信息
   */
  getlocationlist: function (id, type) {
    if (wx.showLoading) {
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
    } else {
      wx.showToast({
        title: '加载中...',
        mask: true,
        duration: app.globalData.toastTimeout,
        icon: 'none',
      })
    }
    let token = wx.getStorageSync('token')
    let that = this
    wx.request({
      url: app.apiUrl('/user/getlocationlist'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        id: id,
      },
      success: function (res) {
        console.log('locations')
        if (res.data.code > app.globalData.successCode) {
          wx.showModal({
            title: '提示',
            content: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            showCancel: false
          })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 0)
        } else {
          let locationTemp = []
          let locationIDTemp = []
          if (res.data.data) {
            for (var i = 0; i < res.data.data.length; i++) {
              locationTemp.push(res.data.data[i].name)
              locationIDTemp.push(res.data.data[i].id)
            }
          }

          if (type == PROVINCE) {
            that.setData({
              provinces: locationTemp,
              provincesID: locationIDTemp
            })
          } else if (type == CITY) {
            that.setData({
              cities: locationTemp,
              citiesID: locationIDTemp
            })
          } else if (type == DISTRICT) {
            that.setData({
              districts: locationTemp,
              districtsID: locationIDTemp
            })
          }
        }
      
      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: '网络请求异常',
          showCancel: false
        })
      },
      complete: function (res) {
        if (wx.showLoading)
          wx.hideLoading()
        else
          wx.hideToast()
      }
    })
  },

  /**
   * 添加地址
   */
  addcontact: function (contact, form_id) {
    let token = wx.getStorageSync('token')
    let that = this
    if (that.data.id != 0) 
      contact.id = that.data.id
    console.log(contact.id)
    wx.request({
      url: app.apiUrl('/user/addcontact'),
      method: 'POST',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        form_id: form_id,
        contact_id: contact.id,
        name: contact.name,
        phone: contact.phone,
        province: contact.selProvince,
        province_id: contact.selProvinceID, 
        city: contact.selCity,
        city_id: contact.selCityID,
        district: contact.selDistrict,
        district_id: contact.selDistrictID,
        address: contact.address
      },
      success: function (res) {
        console.log('addcontact')
        console.log(res.data)
        if (res.data.code > app.globalData.successCode) {
          wx.showToast({
            title: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            icon: 'none',
            duration: 2000
          })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 0)
        } else {
          wx.showToast({
            title: '添加成功',
            icon: 'none',
            duration: 2000
          })
          if (that.data.type == 2) {
            let pages = getCurrentPages();
            let prevPage = pages[pages.length - 2];
            prevPage.setData({
              curAddressData: res.data.data
            })

            prevPage.getConfirm()
          }
          wx.navigateBack({
            delta: 1
          })
          
        }
        
        
      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
        // wx.hideToast()
        //console.log(res)
      }
    })
  },

  /**
   * 获取地址详情
   */
  getAddress: function (id) {

    let token = wx.getStorageSync('token')
    let that = this
    wx.request({
      url: app.apiUrl('/user/addcontact'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        id: id
      },
      success: function (res) {
        console.log('编辑')
        console.log(res.data)
        if (res.data.data) {
          that.setData({
            name: res.data.data.name,
            phone: res.data.data.phone,
            selProvince: res.data.data.province,
            selProvinceID: res.data.data.province_id,
            selCity: res.data.data.city,
            selCityID: res.data.data.city_id,
            selDistrict: res.data.data.district,
            selDistrictID: res.data.data.district_id,
            address: res.data.data.address

          })
          that.getCities(res.data.data.province_id, CITY)
          that.getDistricts(res.data.data.city_id, DISTRICT)
          

        }
      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
        // wx.hideToast()
        //console.log(res)
      }
    })
  }
})
